<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px"
             @keyup.enter.native="handleQuery">
      <el-row>
        <el-form-item label="商品名称" prop="productName">
          <el-input v-model="queryParams.productName" placeholder="请输入商品名称" clearable size="small" class="input-rule"/>
        </el-form-item>
        <el-form-item label="商品分类" prop="categoryUid">
          <el-cascader v-model="queryParams.categoryUid" :options="categoryOptions" clearable filterable
                       class="input-rule">
          </el-cascader>
        </el-form-item>
        <el-form-item style="margin-left: 50px;">
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="row-mb2">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" :disabled="single">添加
        </el-button>
      </el-col>
    </el-row>

    <el-table ref="multipleTable" v-loading="loading" :data="infoList" @selection-change="handleSelectionChange" border
              tooltip-effect="dark">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品图片" align="center" prop="carouselImgOne" width="100">
        <template slot-scope="scope">
          <el-image :z-index="zIndex" v-if="scope.row.carouselImgOne != null && scope.row.carouselImgOne != '' "
                    slot="reference" :src="scope.row.carouselImgOne" class="image-rows"
                    :preview-src-list="[scope.row.carouselImgOne]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="productName"/>
      <el-table-column label="供货价" align="center" prop="costPriceStr"/>
      <el-table-column label="零售价" align="center" prop="retailPriceStr"/>
      <el-table-column label="批发价" align="center" prop="tradePriceStr"/>
      <el-table-column label="库存" align="center" prop="stockNumber" sortable/>
      <el-table-column label="收藏数" align="center" prop="collectNum"/>
      <el-table-column label="销量" align="center" prop="buyNum" sortable/>
      <el-table-column label="更新时间" align="center" prop="updateTime" width="200" sortable>
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span><br/>
          <span>{{ statusFormat(scope.row.dataStatus) }}</span>
        </template>
      </el-table-column>

    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList" :page-sizes="pageSizess"/>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo
} from "@/api/product/info";
import {
  selectOptions
} from "@/api/product/category"

export default {
  name: "product",
  props: {
    uids: {
      type: Array,
      default: []
    },
    productArray: Array,
    default: []
  },
  data() {
    return {
      pageSizess: [5, 10, 15, 20, 25, 30, 50],
      zIndex: 3000,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 多选框传值
      idsHistory: [],
      checkIds: [],
      // 商品
      productList: [],

      // 商品信息表格数据
      infoList: [],
      infoListHistory: [],
      multipleSelection: [],
      // 默认数字
      activeClass: 0,
      //品牌
      brandOptions: [],
      // 商品类别
      categoryOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 5,
        productName: null,
        categoryUid: null,
        brandUid: null,
        minBuyNum: null,
        maxBuyNum: null,
        minCostPirce: null,
        maxCostPirce: null,
        minRetailPrice: null,
        maxRetailPrice: null,
        minTradePrice: null,
        maxTradePrice: null,
        dataStatus: null,
        auditStatus: null,
        stockNumber: null,
        categoryUidOne: null,
        categoryUidTwo: null,
        categoryUidThree: null,

      },
      columns: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {}
    };
  },
  created() {
    this.idsHistory = this.uids;
    this.productList = this.productArray;
    if (this.uids) {
      this.addCheck(this.uids, 2);
    }
    this.getList();
    selectOptions().then(response => {
      this.categoryOptions = response.data;
    });


  },
  methods: {
    oninput(num, limit) {
      var str = num
      var len1 = str.substr(0, 1)
      var len2 = str.substr(1, 1)
      if (str.length > 1 && len1 == 0 && len2 != ".") {
        str = str.substr(1, 1)
      }
      if (len1 == ".") {
        str = ""
      }
      if (str.indexOf(".") != -1) {
        var str_ = str.substr(str.indexOf(".") + 1)
        if (str_.indexOf(".") != -1) {
          str = str.substr(0, str.indexOf(".") + str_.indexOf(".") + 1)
        }
      }
      //正则替换
      str = str.replace(/[^\d^\.]+/g, '') // 保留数字和小数点
      if (limit / 1 === 1) {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/, '$1') // 小数点后只能输 1 位
      } else {
        str = str.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1') // 小数点后只能输 2 位
      }
      return str
    },
    /**
     * 赋值进对象
     * */
    addProductObj(id, check) {
      let arrats = [];
      if (check != 2) {
        if (check == 1) {
          arrats = this.infoList
        } else if (check == 0) {
          //console.log(this.infoListHistory)
          arrats = this.infoListHistory
        }
        arrats.forEach(item => {
          if (id == item.productUid) {
            let productObj = {
              productUid: "",
              productName: "",
              productImg: "",
              stockNumber: "",
              price: ""
            }
            productObj.productUid = item.productUid;
            productObj.productImg = item.carouselImgOne;
            productObj.productName = item.productName;
            productObj.price = item.retailPrice;
            productObj.stockNumber = item.stockNumber;
            this.productList.push(productObj);
          }
        })
      }
    },
    /**
     *  赋值
     * */
    addCheck(arr, check) {
      //let this_ = this;
      //console.log(arr);
      //console.log(this.checkIds)
      if (arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          let index = this.checkIds.indexOf(arr[i] + "");
           // console.log(index)
          if (0 > index) {
            //console.log(arr[i]);
            this.checkIds.push(arr[i] + "");
            this.addProductObj(arr[i], check);
          }
        }
        //console.log(this.checkIds);
         //console.log(this.idsHistory)
        this.idsHistory.forEach((item) => {
          //console.log("check"+this.checkIds)
          let index = arr.indexOf(item);

          if (0 > index) {
            let ind = this.checkIds.indexOf(item + "");
            if (ind > -1) {
              this.checkIds.splice(ind, 1);
            }
          }
        })
        // console.log("check"+this.checkIds)
      } else {

        let size = this.infoListHistory.length;
        for (let i = 0; i < size; i++) {
          let productInfo = this.infoListHistory[i];
          let index = this.checkIds.indexOf(productInfo.productUid + "");
          if (index > -1) {
            this.checkIds.splice(index, 1);
          }
        }
      }

    },
    /** 查询商品信息列表 */
    getList() {
      this.loading = true;
      if (this.queryParams.categoryUid != null && this.queryParams.categoryUid.length > 0) {
        let uidArray = this.queryParams.categoryUid;
        this.queryParams.categoryUidOne = uidArray[0];
        if (uidArray.length > 1) {
          this.queryParams.categoryUidTwo = uidArray[1];
        }
        if (uidArray.length > 2) {
          this.queryParams.categoryUidThree = uidArray[2];
        }
      }
      if (this.infoList) {
        this.infoListHistory = this.infoList;
      }

      listInfo(this.queryParams).then(response => {
        this.infoList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.queryParams.categoryUidOne =  null;
        this.queryParams.categoryUidTwo =  null;
        this.queryParams.categoryUidThree =  null;

        let arr = this.ids;
        //console.log(this.infoListHistory)
        //console./(arr)
        this.addCheck(arr, 0);

        this.checkedBox();
        // console.log(this.checkIds);
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {

          if (this.$refs.multipleTable) {
            this.$nextTick(() => {
              this.$refs.multipleTable.toggleRowSelection(row, true);
            });
          }
        });
      } else {
        if (this.$refs.multipleTable) {
          this.$refs.multipleTable.clearSelection();
        }
      }
    },
    // 取消按钮
    cancel() {
      this.checkIds = [];
      this.productList = [];
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
    if(selection.length>0){
      this.idsHistory = this.ids;
    }


      this.multipleSelection = selection;
      this.ids = selection.map(item => item.productUid)
      this.single = !selection.length > 0
    },
    /** 新增按钮操作 */
    handleAdd() {
      let arr = this.ids;
     // console.log(arr)
      this.addCheck(arr, 1);
      //this.checkedBox();
      //console.log(this.checkIds);
      //console.log(this.productList)
      this.$emit('idsId', this.productList, this.checkIds)
    },
    statusFormat(status) {
      let showStatus = "";
      if (status == "1") {
        showStatus = "销售中";
      } else {
        showStatus = "已下架"
      }
      return showStatus;
    },
    /**
     *  切换页数的选中
     */
    checkedBox() {
      //console.log(this.checkIds);
      if (this.checkIds) {
        let infoArr = this.infoList;
        for (let i = 0; i < infoArr.length; i++) {
          let index = this.checkIds.indexOf(infoArr[i].productUid + "");
          if (index > -1) {
            this.toggleSelection([this.infoList[i]])
          }
        }
      }
    }
  }
};
</script>

<style scoped>
.input-rule {
  width: 232.45px;
}

.row-mb2 {
  margin: -7.5px -7.5px 7.5px -7.5px;
}
</style>
